{{if false}}<script>{{/if}}
{{$controller = $smarty.const.CCTRL}}
{{$token = $smarty.const.TOKEN}}
function handleEvents(){
    try{
        acolumns['CategoryName'].createeditor=function (row, cellvalue, editor) {
            editor.jqxDropDownList({ source: {{$acategorys|@json_encode}} });
        };
        acolumns['UnitPrice'].createeditor=function (row, cellvalue, editor) {
            editor.jqxNumberInput({ decimalDigits: 2 });
        };
        acolumns['UnitPrice'].validation= function (cell, value) {
            if (value < 0 || value > 1000000) {
                return { result: false, message: "Unit Price should be in the 0-1,000,000 interval" };
            }
            return true;
        };
        acolumns['UnitsOnOrder'].createeditor=function (row, cellvalue, editor) {
            editor.jqxNumberInput({ decimalDigits: 2 });
        };
        acolumns['UnitsOnOrder'].validation= function (cell, value) {
            if (value < 0 || value > 1000000) {
                return { result: false, message: "Units On Order should be in the 0-1,000,000 interval" };
            }
            return true;
        };
        acolumns['ProductName'].validation= function (cell, value) {
            if (value =="") {
                return { result: false, message: "Product Name should be non-empty." };
            }
            return true;
        };
        myGrid.bind('cellendedit', function (event) {
            try{
                var args = event.args;
                var _column = args.datafield ,_row = args.rowindex,_value = args.value;
                var _data=myGrid.jqxGrid('getrowdata', _row);
                var _id=_data.ProductID;
                if(_id==undefined || _id==""){
                    return;
                }
                switch(_column){
                    case "Status":
                        if(_value=="true" || _value ==true) _value="Public";
                        else _value="Private";
                        updateCol(_column,_id,_value);
                        break;
                    case "CategoryName":
                        var _re={{$reacategorys|@json_encode}};
                        if(_value!=_data.CompanyName)updateCol("Categorys",_id,_re[_value]);
                        break;
                    case "ProductName":
                        if(_value!=_data.ProductName)updateCol(_column,_id,_value);
                        break;
                    case "Supplier":
                        if(_value!=_data.Supplier)updateCol(_column,_id,_value);
                        break;
                    case "QuantityPerUnit":
                        if(_value!=_data.QuantityPerUnit)updateCol(_column,_id,_value);
                        break;
                    case "UnitPrice":
                        if(_value!=_data.UnitPrice)updateCol(_column,_id,_value);
                        break;
                    case "UnitsOnOrder":
                        if(_value!=_data.UnitsOnOrder)updateCol(_column,_id,_value);
                        break;
                    default:
                    uiMessage("Unkown this cell. Maybe 'editable' of this colums is 'off'."); 
                }
            }catch(e){
                uiMessage(e.message);
                console.log("Error:"+e.message);
            }
        });
    }catch(e){tipMessage(e.message);}
}
function delete_selected_record(un){
    try{
        var cells = myGrid.jqxGrid('getselectedcells');
        
        var _ids=new Array();
        if(cells.length>0){
            for(var i=0;i<cells.length;i++){
                if(cells[i].rowindex!=undefined){
                    var _dataRow=myGrid.jqxGrid('getrowdata', cells[i].rowindex);
                    var _id=_dataRow._id==undefined?(_dataRow.ID==undefined?_dataRow.ProductID:_dataRow.ID):_dataRow._id;
                    if(_id!=undefined && !_ids.in_array(_id)){
                        _ids.push(_id);
                    }
                }
            }
            if(_ids.length>0){
                var url,data,tit;
                if(un==true){
                    url="{{base_url()}}backend/{{$controller}}/restore/{{$token}}";
                    tit="Do you want restore selected record?<br/>";
                }else{
                    url="{{base_url()}}backend/{{$controller}}/delete/{{$token}}";
                    tit="Do you want delete selected record?<br/>";
                }
                ShowConfirmDialogMessage(tit+_ids.length+" record","Confirm?",function(){
                    CloseConfirmDialogMessage();
                    console.log("Delete:\nIDs:"+_ids+" ↵ Call");
                    data={
                        _id      :   _ids
                    }
                    isrunning=true;
                    myAjax(url,data,function(o){
                        isrunning=false;
                        if(o.result>=0){
                            uiMessage(o.message);
                            myGrid.jqxGrid('updatebounddata');
                        }else{
                            ShowErrorDialogMessage(o.message);
                        }
                    });
                });
            }else{
                uiMessage("No row selected. Please select one or more rows.");
            }
        }else{
            uiMessage("No row selected. Please select one or more rows.");
        }
    }catch(e){
        console.log("JSON Error:"+e.message+"\n↵ Error");
        uiMessage(e.message);
        //ShowErrorDialogMessage("Sorry. Your request could not be completed.<br/> Please check your input data.");
    }
}
function change_status_selected_record(_status){
    try{
        _status=_status=='true'?'Public':'Private';
        var cells = myGrid.jqxGrid('getselectedcells');
        var _ids=new Array();
        if(cells.length>0){
            for(var i=0;i<cells.length;i++){
                if(cells[i].rowindex!=undefined){
                    var _dataRow=myGrid.jqxGrid('getrowdata', cells[i].rowindex);
                    var _id=_dataRow._id==undefined?(_dataRow.ID==undefined?_dataRow.ProductID:_dataRow.ID):_dataRow._id;
                    if(_id!=undefined && !_ids.in_array(_id)){
                        _ids.push(_id);
                    }
                }
            }
            if(_ids.length>0){
                ShowConfirmDialogMessage("Do you want change status of selected record?<br/>"+_ids.length+" record","Delete?",function(){
                    CloseConfirmDialogMessage();
                    console.log("Status:\nIDs:"+_ids+" ↵ Call");
                    var url,data;
                    url="{{base_url()}}backend/{{$controller}}/changestatus/{{$token}}";
                    data={
                        _id     :   _ids,
                        _status :   _status
                    }
                    isrunning=true;
                    myAjax(url,data,function(o){
                        isrunning=false;
                        if(o.result>=0){
                            uiMessage(o.message);
                            myGrid.jqxGrid('updatebounddata');
                        }else{
                            ShowErrorDialogMessage(o.message);
                        }
                    });
                });
            }else{
                uiMessage("No row selected. Please select one or more rows.");
            }
        }else{
            uiMessage("No row selected. Please select one or more rows.");
        }
    }catch(e){
        console.log("JSON Error:"+e.message+"\n↵ Error");
        uiMessage(e.message);
        //ShowErrorDialogMessage("Sorry. Your request could not be completed.<br/> Please check your input data.");
    }
}
function updateCol(_col,_id,_value){
    try{
        var url,data;
        url="{{base_url()}}backend/product/column_update/{{$token}}/"+_col;
        data={
            _id      :   _id,
            _value   :   _value
        }
        isrunning=true;
        myAjax(url,data,function(o){
            isrunning=false;
            if(o.result>=0){
                uiMessage(o.message);
            }else{
                uiMessage(o.message);
                //ShowNoticeDialogMessage(result.msg);
            }
        });
    }catch(e){
        console.log("JSON Error:"+e.message+"\n↵ Error");
        uiMessage(e.message);
        //ShowErrorDialogMessage("Sorry. Your request could not be completed.<br/> Please check your input data.");
    }
}
function SaveItem(){
    try{
        if(isrunning)return;
        console.log("Save ↵ Call");
        var url="{{base_url()}}backend/{{$controller}}/save";
        var data={
            _id             :   $("#txtID").val(),
            _name           :   $("#txtProductName").val(),
            _alias          :   $("#txtAlias").val(),
            _title          :   $("#txtTitle").val(),
            _image          :   $("#txtImage").val(),
            _category       :   $("#cbxCategory").val(),
            _supplier       :   $("#txtSupplier").val(),
            _unitprice      :   $("#txtUnitPrice").val(),
            _unitsonorder   :   $("#txtUnitOnOrder").val(),
            _quantity       :   $("#txtQuantity").val(),
            _tag            :   $("#txtTag").val()
        }
        //ShowNoticeDialogMessage($("<div />").text(Content).html());return;
        console.log(data);
        isrunning=true;
        myAjax(url,data,function(data){
            isrunning=false;
            if(data.result>=0){
                uiMessage(data.message)
                myjqxGrid.CancelEdit();
                myjqxGrid.Refresh();
            }else{
                ShowErrorDialogMessage(data.message);
            }
        });
    }catch(e){
        console.log("JSON Error:"+e.message+"\n↵ Error");
        ShowErrorDialogMessage(e.message);
        //ShowErrorDialogMessage("Sorry. Your request could not be completed.<br/> Please check your input data.");
    }
}